#!/bin/bash
set -e

destdir="$1"
shift 1
qtdir="$1"
shift 1

mkdir -p "$destdir/lib/imageformats"
mkdir -p "$destdir/lib/iconengines"
mkdir -p "$destdir/lib/platforms"

{
	echo '[Paths]'
	echo 'Plugins=../lib'
} > "$destdir/bin/qt.conf"

filetofix=`mktemp`
filetofixnew=`mktemp`
otooloutput=`mktemp`
find "$destdir" -type f > "$filetofix"
while read f; do
	case "$f" in
		*.dll|*.exe)
			strip "$f"
			;;
		*)
			:
			;;
	esac
done < "$filetofix"

for p in `cd $qtdir/plugins/imageformats; ls`; do
	case "$p" in
		*d.dll)
			:
			;;
		*)
			cp -R "$qtdir/plugins/imageformats/$p" "$destdir/lib/imageformats/$p"
			chmod -R u+w "$destdir/lib/imageformats/$p"
			echo "$destdir/lib/imageformats/$p" >> "$filetofix"
			;;
	esac
done
for p in `cd $qtdir/plugins/imageformats; ls`; do
	case "$p" in
		*d.dll)
			if [ ! -e "$destdir/lib/imageformats/${p%d.dll}.dll" ]; then
				cp -R "$qtdir/plugins/imageformats/$p" "$destdir/lib/imageformats/$p"
				chmod -R u+w "$destdir/lib/imageformats/$p"
				echo "$destdir/lib/imageformats/$p" >> "$filetofix"
			fi
			;;
	esac
done
for p in `cd $qtdir/plugins/iconengines; ls`; do
	case "$p" in
		*d.dll)
			:
			;;
		*)
			cp -R "$qtdir/plugins/iconengines/$p" "$destdir/lib/iconengines/$p"
			chmod -R u+w "$destdir/lib/iconengines/$p"
			echo "$destdir/lib/iconengines/$p" >> "$filetofix"
			;;
	esac
done
for p in `cd $qtdir/plugins/iconengines; ls`; do
	case "$p" in
		*d.dll)
			if [ ! -e "$destdir/lib/iconengines/${p%d.dll}.dll" ]; then
				cp -R "$qtdir/plugins/iconengines/$p" "$destdir/lib/iconengines/$p"
				chmod -R u+w "$destdir/lib/iconengines/$p"
				echo "$destdir/lib/iconengines/$p" >> "$filetofix"
			fi
			;;
	esac
done
cp -R "$qtdir/plugins/platforms/qwindows.dll" "$destdir/lib/platforms/qwindows.dll"
chmod -R u+w "$destdir/lib/platforms/qwindows.dll"
echo "$destdir/lib/platforms/qwindows.dll" >> "$filetofix"

while [ -s "$filetofix" ]; do
	> "$filetofixnew"
	while read f; do
		objdump -p "$f" | grep -a 'DLL Name:' | sed 's,^.*DLL Name:\s*\(.*\)$,\1,' > "$otooloutput"
		while read l; do
			l=`which "$l"`
			case "$l" in
				/c/Windows/*)
					:
					;;
				*.dll)
					destfile="$(basename $l)"
					if [ ! -e "$destdir/bin/$destfile" ]; then
						cp -R "$l" "$destdir/bin/"
						chmod -R u+w "$destdir/bin/$destfile"
						echo "$destdir/bin/$destfile" >> "$filetofixnew"
					fi
					;;
				*)
					echo "How to handle this?" >&2
					echo "'$l'" >&2
					exit -1
					;;
			esac
		done < "$otooloutput"
	done < "$filetofix"
	mv "$filetofixnew" "$filetofix"
done
rm -f "$filetofix"
rm -f "$filetofixnew"
rm -f "$otooloutput"
zipfile="`pwd`/$1.zip"
shift 1
destname=$(basename "$destdir")
cd "$destdir/.."; zip -r "$zipfile" "$destname"
exit 0
